package au.com.bus4u.shiro;

import au.com.bus4u.common.Constast;
import au.com.bus4u.service.EmailService;
import au.com.bus4u.service.UserService;
import au.com.bus4u.utils.PageData;
import lombok.extern.java.Log;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/**
 * 自定义Realm
 */
@Log
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private EmailService emailService;

    /**
     * 执行授权逻辑
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        log.info("执行授权逻辑");
        //获取用户
        String phone = principals.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        try {

            Set<String> roles = userService.findRolesByPhone(phone);

            Integer role_id = userService.findRoleIDByPhone(phone);
//            log.info("role_id = "+role_id);

//            if(Constast.USER_TYPE_SuperAdmin == role_id){
//                log.info("超级管理员获取所有权限");
//                info.addStringPermission("*:*");
//            }else{
//                log.info("获取"+roles.toString()+"权限数据");
                Set<String> permissionsByRoleID = userService.findPermissionsByRoleID(role_id);
//                System.err.println("permissionsByRoleID = " + permissionsByRoleID);
                info.setStringPermissions(userService.findPermissionsByRoleID(role_id));

//            }

            //获取用户角色(角色通用权限)
            info.setRoles(roles);
        } catch (Exception e) {
//            log.info("获取角色权限数据失败");
            e.printStackTrace();
        }


        return info;
    }

    /**
     * 执行登陆认证逻辑
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        log.info("执行登陆认证逻辑");
        String phone=token.getPrincipal().toString();//UsernamePasswordToken的第一个参数
//        log.info("电话为:"+phone + "的账户执行了登陆操作!");
        List<PageData> userList = null;
        try {
            userList = userService.findByPhone(phone);
        } catch (Exception e) {
            e.printStackTrace();
        }

        /**
         * SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
         * 其中principal是账号信息，
         * hashedCredentials是MD5加密后的密码，
         * credentialsSalt是密码加密的盐值，
         * realmName为当前realm对象的name。
         */
        if(userList!=null && userList.size() > 0 && userList.get(0)!=null){
//            log.info("数据库密码："+userList.get(0).get("password"));
            int status = (int)userList.get(0).get("status");
            AuthenticationInfo authcInfo = null;
            if(status == 0){
                authcInfo=new SimpleAuthenticationInfo(userList.get(0).get("phone"),userList.get(0).get("password"),this.getClass().getName());//第三个参数不能为空的任意字符
            }else if(status == 1){
                throw new LockedAccountException("账号被冻结");
            }else if(status == 2){
                //发送验证邮件，然后抛出异常提示用户进入注册邮箱激活
                emailService.sendUserRegistValidationEmail(userList.get(0).get("user_id").toString(),userList.get(0).get("user_email").toString());
//                log.info(userList.get(0).get("user_email")+":邮箱未激活，系统已发送验证邮件到该邮箱");
                throw new LockedAccountException("邮箱未激活,请进入注册邮箱接收验证邮件");
            }
            return authcInfo;
        }else{
            return null;
        }
    }
}
